package com.fowo.api.service.handleWork;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.util.k3cloud.domain.Authentication;
import com.fowo.api.datainterface.util.k3cloud.domain.BillSave;
import com.fowo.api.entity.*;
import com.fowo.api.model.payable.PayablePushJinideAction;
import com.fowo.api.model.payable.PayableVo;

import com.fowo.api.service.handleWork.jindieEntity.jindieResult;
import com.fowo.api.service.handleWork.jindieEntity.jindieVoucher;
import com.fowo.api.service.impl.*;
import com.fowo.api.util.LocalDateUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class payablePushJinide implements PayablePushJinideAction {
    @Resource
    private PayableServiceImpl payableService;
    @Resource
    protected PayableProductServiceImpl payableProductService;
    @Resource
    private BdSupplierServiceImpl bdSupplierService;

    @Resource
    private SupplierServiceImpl supplierService;
    @Resource
    private BosAssistantdataDetailServiceImpl bosAssistantdataDetailService;
    @Resource
    private WarehouseServiceImpl warehouseService;


    private static final Authentication auth=new Authentication("64e8964fb4af0d","Administrator","a@123456");

    private static final K3CloudTemplate k3loudTemplate=new K3CloudTemplate("http://121.225.97.82:8001/K3cloud/",auth);
    //应付单 推送金蝶
    @Override
    public void run(Long id) throws Exception {
        //获取付款单
        PayableVo voById = payableService.getVoById(id);
        Assert.notNull(voById,"单据不存在!");
        Assert.isTrue(voById.getPushStatus().equals("0")||voById.getPushStatus().equals("2"),"已推送不能重复!");
        Assert.isTrue(voById.getStauts().equals("1"),"单据未审核不能推送!");
        Assert.notNull(voById.getProductType(),"商品类型不能为空!");
        Assert.notNull(voById.getSettlementDate(),"结算日期不能为空!");
        //查询金蝶需要推送的供应商
        Supplier byId = supplierService.getById(voById.getSupplierId());
        Assert.notNull(byId,"供应商信息不存在!");
        BdSupplier one = bdSupplierService.getOne(Wrappers.<BdSupplier>query().lambda().eq(BdSupplier::getShortName, byId.getSupplierName()));
        Assert.notNull(one,byId.getSupplierName()+"供应商信息在金蝶中不存在！");
        List<PayableProduct> list1 = payableProductService.list(Wrappers.<PayableProduct>query().lambda().eq(PayableProduct::getParentPayable, id));
        BigDecimal reduce = list1.stream().map(PayableProduct::getSubtotal).reduce(BigDecimal.ZERO, BigDecimal::add);


        Assert.notNull(voById.getWarehouse(),"请选择仓库!");
        Warehouse byId1 = warehouseService.getById(voById.getWarehouse());
        Assert.notNull(byId1,"仓库信息不存在!");
        //查询仓库
        BosAssistantdataDetail cangku = bosAssistantdataDetailService.getOne(Wrappers.<BosAssistantdataDetail>query().lambda().eq(BosAssistantdataDetail::getDataValue, byId1.getName()).eq(BosAssistantdataDetail::getFid,"6402bc823586b8"));
        Assert.notNull(cangku,"仓库信息在金蝶中不存在!");

        //6402bc823586b8

        BillSave billSave = new BillSave("GL_VOUCHER");
        jindieVoucher jindieVoucher=new  jindieVoucher();
        jindieVoucher.setIsAutoAdjustField("true");
        jindieVoucher.ModelDTO  modelDTO=new jindieVoucher.ModelDTO();
        modelDTO.setFvoucherid(0);
        //账簿
        jindieVoucher.ModelDTO.FAccountBookIDDTO FAccountBookIDDTO=new  jindieVoucher.ModelDTO.FAccountBookIDDTO();
        FAccountBookIDDTO.setFNumber("002");//多组织切换账簿002  是苏发  泽壹是007
        modelDTO.setFAccountBookID(FAccountBookIDDTO);
        modelDTO.setFDate(LocalDateUtils.format(voById.getSettlementDate(),LocalDateUtils.DATE_PATTERN));//日期
        //凭证字
        jindieVoucher.ModelDTO.FVOUCHERGROUPIDDTO FVOUCHERGROUPIDDTO=new jindieVoucher.ModelDTO.FVOUCHERGROUPIDDTO();
        FVOUCHERGROUPIDDTO.setFNumber("PRE001");
        modelDTO.setFvouchergroupid(FVOUCHERGROUPIDDTO);
        modelDTO.setFvouchergroupno("1");
        modelDTO.setFDocumentStatus("Z");
        List<jindieVoucher.ModelDTO.FEntityDTO> list=new ArrayList<>();
        String keMu="1403";
        String beizhu="原材料入库,单号:"+voById.getPayCode();
        Assert.isTrue(!voById.getProductType().equals("3"),"暂时不支持加工单推送!");
        if(voById.getProductType().equals("1")){
            keMu="1405.01";
            beizhu="成品入库,单号:"+voById.getPayCode();
        }
        jindieVoucher.ModelDTO.FEntityDTO entity = createEntity(keMu,reduce.doubleValue(),null,null,voById.getPayCode(),beizhu,cangku.getNumber());
        //01001
        jindieVoucher.ModelDTO.FEntityDTO entity1 = createEntity("2202.02",null,reduce.doubleValue(),one.getNumber(),voById.getPayCode(),beizhu,null);
        list.add(entity);
        list.add(entity1);
        modelDTO.setFEntity(list);
        jindieVoucher.setModel(modelDTO);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(jindieVoucher, false, false);
        billSave.setModel(stringObjectMap);
        String result = k3loudTemplate.executeBillSave(billSave, String.class);
        jindieResult jindieResult = JSONObject.parseObject(result, jindieResult.class);
        if(jindieResult.getResult().getResponseStatus().getIsSuccess().equals("true")){
            voById.setPushStatus("1");
            voById.setResultInfo("推送完成");
        }else{
            voById.setPushStatus("2");
            voById.setResultInfo(jindieResult.getResult().getResponseStatus().getErrors().toString());
        }
        payableService.updateById(voById);
    }

    private static jindieVoucher.ModelDTO.FEntityDTO createEntity(String kemu,Double jiefang,Double daifang,String gongchang,String code,String beizhu,String cangku){
        jindieVoucher.ModelDTO.FEntityDTO fEntityDTO=new jindieVoucher.ModelDTO.FEntityDTO();
        //科目编码
        jindieVoucher.ModelDTO.FEntityDTO.FACCOUNTIDDTO FACCOUNTIDDTO=new jindieVoucher.ModelDTO.FEntityDTO.FACCOUNTIDDTO();
        FACCOUNTIDDTO.setFNumber(kemu);
        fEntityDTO.setFaccountid(FACCOUNTIDDTO);
        fEntityDTO.setFexplanation(beizhu);
//        if(kemu.equals("1403")){
//            fEntityDTO.setFexplanation("原材料入库,单号:"+code);
//        }else{
//            fEntityDTO.setFexplanation("成品入库,单号:"+code);
//        }
        //币别
        jindieVoucher.ModelDTO.FEntityDTO.FCURRENCYIDDTO  FCURRENCYIDDTO=new jindieVoucher.ModelDTO.FEntityDTO.FCURRENCYIDDTO();
        FCURRENCYIDDTO.setFNumber("PRE001");
        fEntityDTO.setFcurrencyid(FCURRENCYIDDTO);
        //汇率
        jindieVoucher.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO FEXCHANGERATETYPEDTO=new jindieVoucher.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO();
        FEXCHANGERATETYPEDTO.setFNumber("HLTX01_SYS");
        fEntityDTO.setFexchangeratetype(FEXCHANGERATETYPEDTO);
        //借方金额
        fEntityDTO.setFdebit(jiefang);//
//        fEntityDTO.setFexchangerate(1.0);
        fEntityDTO.setFamountfor(jiefang!=null?jiefang:daifang);//原币金额
//        fEntityDTO.setFAmount(jiefang!=null?jiefang:daifang);
        // 贷方金额
        fEntityDTO.setFcredit(daifang);
        jindieVoucher.ModelDTO.FEntityDTO.FDetailIDDTO FDetailIDDTO=new jindieVoucher.ModelDTO.FEntityDTO.FDetailIDDTO();
        //设置供应商
        if(gongchang!=null){

            jindieVoucher.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX4DTO  FDETAILIDFFLEX4DTO=new  jindieVoucher.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX4DTO();
            FDETAILIDFFLEX4DTO.setFNumber(gongchang);
            FDetailIDDTO.setFDETAILID__FFLEX4(FDETAILIDFFLEX4DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //设置仓库
        if(cangku!=null){
            jindieVoucher.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100004DTO  FDETAILIDFF100004DTO=new  jindieVoucher.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100004DTO();
            FDETAILIDFF100004DTO.setFNumber(cangku);
            FDetailIDDTO.setFDETAILID__FF100004(FDETAILIDFF100004DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }

        return fEntityDTO;
    }

}
